
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Diagnostics;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;
using Swaf.Security;
using UserLogin;

namespace UserManagement
{
    public class MembershipsBizRules : Syrinx.BaseBizRules
    {		
		public IBizObjList getCostsTimeType(IApplication app, IRuleContext context)
		{
			return app.appData["membershipsOptions.costTimeTypes"] as IBizObjList;
		}
		public IBizObjList getMembershipVisibility(IApplication app, IRuleContext context)
		{
			return app.appData["membershipsOptions.visibilities"] as IBizObjList;
		}
        public IBizObjList getCompanyMemberships(IApplication app, IRuleContext context, Swaf.BGuid.Guid companyId, string userVisibility)
        {
            FlexiMap m = new FlexiMap();
            m["companyId"] = companyId;
            m["userVisibility"] = userVisibility;
            IBizObjList memberships = null;
            if(userVisibility != null && userVisibility != "")
                memberships = app.appData.get("Data.CompanyMembership.GetMembershipsForUserVisibility", m) as IBizObjList;
            else
                memberships = app.appData.get("Data.CompanyMembership.GetMemberships", m) as IBizObjList;
			return memberships;
        }
		
		public IBizObj getCompanyMembershipDetail(IApplication app, IRuleContext context, IBizObj membership)
		{
			try
			{
				IResults rc = app.ruleMgr.execute("getArticleLimit", membership);
				if (rc.ExceptionInfo != null)
					throw new UserManagementException("error executing getCompanyMembershipCostDetail", rc.ExceptionInfo);
				membership.put("limits", rc.CallResults);
				return membership;
			}
			catch (Exception e)
			{
				throw new UserManagementException("error executing getCompanyMembershipDetail", e);
			}

		}
		public IBizObj getCompanyMembershipCostDetail(IApplication app, IRuleContext context, IBizObj cost)
		{
			return cost;
		}
		public IBizObjList getMembershipCosts(IApplication app, IRuleContext context, Swaf.BGuid.Guid membershipId)
		{
			FlexiMap m = new FlexiMap();
			m["id"] = membershipId;
			IBizObjList list = app.appData.get("DA.CompanyMembership.GetMembershipCosts", m) as IBizObjList;
			return list;
		}
        public void addNewCompanyMembership(IApplication app, IRuleContext context, IBizObj membership)
		{
			try
			{
				FlexiMap m = new FlexiMap();
				m["companyId"] = ActiveCompanyId;
				m["membership"] = membership;
				app.appData.put("Data.CompanyMembership.AddMembership", m);
				foreach (IBizObj cost in (IBizObjList)membership.get("costs"))
				{
					m["cost"] = cost;
					app.appData.put("Data.CompanyMembership.AddMembershipCost", m);
				}

				if (!(bool)membership.get("createsNewCompany"))
				{
					IBizObj obj = app.bizObjMgr.create("UserGroup");
					obj.put("id", membership.get("id"));
					obj.put("name", membership.get("name"));
					obj.put("description", membership.get("description"));
					IResults rc = app.ruleMgr.execute("addGroup", obj);
					if (rc.ExceptionInfo != null)
						throw new UserManagementException("error executing addGroup in addNewCompanyMembership", rc.ExceptionInfo);
				}
			}
			catch (Exception e)
			{
				throw new UserManagementException("error executing addnewCompanyMembership", e);
			}
		}

        public void updateCompanyMembership(IApplication app, IRuleContext context, IBizObj membership)
        {
			try{
            IBizObjList costs = membership.get("costs") as IBizObjList;
            for (int p = 0; p < costs.numElements; ++p)
                if (costs[p].get("timeLength").Equals(0))
                    costs.removeAt(p--);
            app.appData.put("Data.CompanyMembership.UpdateMembership", membership);
			membership.put("dateUpdated", DateTime.Now);
			app.appData.put("Data.UserManagement.UpdateGroup", membership);
			if (costs.numElements > 0)
			{
				FlexiMap m = new FlexiMap();
				m["membershipId"] = membership.get("id");
				m["companyId"] = ActiveCompanyId;
				app.appData.put("Data.CompanyMembership.ClearCosts", membership);
				foreach (IBizObj cost in costs)
				{
					m["cost"] = cost;
					app.appData.put("Data.CompanyMembership.AddMembershipCost", m);
				}
			}
			if (membership.containsField("limits") && membership.get("limits") != null)
			{
				IResults rc = app.ruleMgr.execute(context, "updateArticleLimit", membership.get("limits") as IBizObj);
				if (rc.ExceptionInfo != null)
					throw new Exception("error executing updateArticleLimit from updateCompanyMembership", rc.ExceptionInfo);
			}
			}catch(Exception e)
			{
				//TODO: 
			}
        }
		public void updateMembershipCost(IApplication app, IRuleContext context, IBizObj cost,Swaf.BGuid.Guid membershipId)
		{
			try
			{
				FlexiMap m = new FlexiMap();
				m["companyId"] = ActiveCompanyId;
				m["membershipId"] = membershipId;
				m["cost"] = cost;
				app.appData.put(string.Format("Data.CompanyMembership.{0}", cost.isNew ? "AddMembershipCost" : "UpdateMembershipCost"), m);
			}
			catch (Exception e)
			{
				
			}
		}
		public IBizObj postExtends_getUserMembershipDetail(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			IBizObj bizobj = returnValue as IBizObj;
			if (bizobj !=null && "User".Equals(bizobj.type.Name))
			{
				IBizObj membership = app.appData.get("DA.CompanyMembership.GetUserMembership", bizobj) as IBizObj;
				if (membership == null)
					membership = app.appData.get("DA.CompanyMembership.GetUserDefaultMembership", bizobj) as IBizObj;
				bizobj.put("membership", membership);
			}
			return bizobj;
		}
		public void postExtends_updateCompanyMembership(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			IBizObj bizobj = inputParams[2] as IBizObj;
			if (bizobj != null && bizobj.containsField("limits"))
			{
				IResults rc = app.ruleMgr.execute(context, "updateArticleLimits", bizobj.get("limits") as IBizObj);
				if (rc.ExceptionInfo != null)
					throw new UserManagementException("error executing updateArticleLImits from updateCompanyLimits", rc.ExceptionInfo);
			}
		}
        public void deleteAllCompanyMemberships(IApplication app, IRuleContext context, Swaf.BGuid.Guid companyId)
        {
            FlexiMap m = new FlexiMap();
            m["companyId"] = companyId;
            app.appData.put("Data.CompanyMembership.DeleteMemberships", m);
        }

        public void deleteCompanyMembership(IApplication app, IRuleContext context, Swaf.BGuid.Guid membershipId)
        {
            FlexiMap m = new FlexiMap();
            m["id"] = membershipId;
            app.appData.put("Data.CompanyMembership.DeleteMembership", m);
            app.appData.put("Data.CompanyMembership.ClearCosts", m);
        }

        public void enrollUserInMembership(IApplication app, IRuleContext context, IBizObj user)
        {
			try
			{
				app.appData.put("Data.CompanyMembership.EnrollUserInMembership", user);
				IBizObjList userGroups = user.get("groups") as IBizObjList;
				IBizObj group = userGroups.insertNew();
				group.put("id", user.get("membership.id"));
				group.put("name", user.get("membership.name"));
				IResults rc = app.ruleMgr.execute("setUserUserGroupMembership", user.get("id"), null, userGroups);
				if (rc.ExceptionInfo != null)
					throw rc.ExceptionInfo;
			}
			catch (Exception e)
			{

			}
        }
    }
}
